import React from 'react'
import { connect } from 'react-redux'

const Todolist = (props) => {
	let { inputVal, inputChange, clickBtn, list, delItem } = props
	let handleKeyDown = (e) => {
		if (e.keyCode === 13) {
			clickBtn()
		}
	}
	return (
		<div onKeyDown={(e) => handleKeyDown(e)}>
			<div>
				<input value={inputVal} onChange={inputChange} />
				<button onClick={clickBtn}>增加</button>
			</div>
			<ul>
				{list.map((e, i) => (
					<li onClick={() => delItem(i)} key={e + i}>
						{e}
					</li>
				))}
			</ul>
		</div>
	)
}

const stateToProps = (state) => {
	return {
		inputVal: state.inputVal,
		list: state.list,
	}
}

const dispatchToProps = (dispatch) => {
	return {
		inputChange(e) {
			let action = {
				type: 'inputChange',
				value: e.target.value,
			}
			dispatch(action)
		},
		clickBtn() {
			let action = {
				type: 'addItem',
			}
			dispatch(action)
		},
		delItem(i) {
			console.log(i)
			let action = {
				type: 'delItem',
				value: i,
			}
			dispatch(action)
		},
	}
}

export default connect(stateToProps, dispatchToProps)(Todolist)
